/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.DetalleCompra;
import com.jjsoft.celularessuc.gco.mdl.FacturaCompra;
import com.jjsoft.celularessuc.gco.mdl.Proveedor;
import com.jjsoft.celularessuc.gco.neg.ArticuloManager;
import com.jjsoft.celularessuc.gco.neg.FacturaCompraManager;
import com.jjsoft.celularessuc.gco.neg.ProveedorManager;
import com.jjsoft.celularessuc.gco.neg.SerieManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.CSelecciones;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import com.jjsoft.celularessuc.gco.util.Validacion;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author Johnny
 */
public class VFacturaCompra extends javax.swing.JFrame {

    /**
     * Creates new form VFacturaCompra
     */
    ArticuloManager am = new ArticuloManager();
    ProveedorManager pm = new ProveedorManager();
    SerieManager sm = new SerieManager();
    List<Proveedor> listaProveedores = new ArrayList<Proveedor>();
    FacturaCompra factura;
    MiModelo modelo = new MiModelo();
    FacturaCompraManager fcm = new FacturaCompraManager();

    public VFacturaCompra() {
        initComponents();
        listaProveedores = pm.listarProveedores();
        for (Proveedor prov : listaProveedores) {
            cboProveedor.addItem(prov.getNombre());
        }
        lblSucursal.setText("SUCURSAL: " + configuraciones.getInstance().getSucursal().getNombre());
        dtFechaInicio.setDate(new Date());
        String[] identificadores = {"CANT", "DESCRIPCION", "P. UNIT", "V. COMPRA"};
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgFactura.setModel(this.modelo);
        this.dtgFactura.getColumn("CANT").setPreferredWidth(30);
        this.dtgFactura.getColumn("DESCRIPCION").setPreferredWidth(330);
        this.dtgFactura.getColumn("P. UNIT").setPreferredWidth(50);
        this.dtgFactura.getColumn("V. COMPRA").setPreferredWidth(50);
        factura = new FacturaCompra();
        factura.setDetalleCompraList(new ArrayList<DetalleCompra>());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cboProveedor = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtNumFactura = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        dtFechaInicio = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        txtGuiaRemision = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel9 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JSpinner();
        jLabel11 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        cmdAgregar = new javax.swing.JButton();
        cmdNuevo = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgFactura = new javax.swing.JTable();
        cmdQuitar = new javax.swing.JButton();
        txtSubtotal = new javax.swing.JTextField();
        txtDescuento = new javax.swing.JSpinner();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtSubtotalD = new javax.swing.JTextField();
        txtIVA = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        cmdGuardar = new javax.swing.JButton();
        jLabel17 = new javax.swing.JLabel();
        cmdAgregar1 = new javax.swing.JButton();
        jLabel18 = new javax.swing.JLabel();
        txtPrecioVenta = new javax.swing.JTextField();
        lblSucursal = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("FACTURA DE COMPRA");

        jLabel2.setText("Proveedor:");

        jLabel3.setText("Numero Factura:");

        jLabel4.setText("Fecha:");

        dtFechaInicio.setDateFormatString("yyyy-MM-dd");

        jLabel5.setText("Guía Remisión:");

        jLabel9.setText("Codigo:");

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel10.setText("Cantidad:");

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        jLabel11.setText("P.Comp");

        txtPrecio.setEditable(false);
        txtPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioKeyReleased(evt);
            }
        });

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        cmdNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/new.png"))); // NOI18N
        cmdNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdNuevoActionPerformed(evt);
            }
        });

        dtgFactura.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgFactura);

        cmdQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdQuitar.setText("    Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        txtSubtotal.setEnabled(false);

        txtDescuento.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        txtDescuento.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                txtDescuentoStateChanged(evt);
            }
        });

        jLabel13.setText("Descuento:");

        jLabel14.setText("Subtotal_D:");

        txtSubtotalD.setEnabled(false);

        txtIVA.setEnabled(false);

        jLabel16.setText("Total:");

        txtTotal.setEditable(false);
        txtTotal.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        txtTotal.setForeground(new java.awt.Color(255, 0, 0));

        jLabel15.setText("IVA:");

        jLabel12.setText("Subtotal_0:");

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        jLabel17.setText("%");

        cmdAgregar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit21.png"))); // NOI18N
        cmdAgregar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregar1ActionPerformed(evt);
            }
        });

        jLabel18.setText("P.Vent");

        txtPrecioVenta.setEditable(false);
        txtPrecioVenta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioVentaKeyReleased(evt);
            }
        });

        lblSucursal.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
        lblSucursal.setForeground(new java.awt.Color(26, 45, 245));
        lblSucursal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblSucursal.setText("lbl1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmdQuitar)
                            .addComponent(cmdGuardar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtDescuento)
                                .addComponent(txtSubtotal)
                                .addComponent(txtSubtotalD, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtIVA, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel17))
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel18)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPrecioVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdAgregar1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtNumFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(81, 81, 81)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtGuiaRemision, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(lblSucursal, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(cboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addComponent(dtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(txtNumFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtGuiaRemision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11)
                            .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmdAgregar)
                            .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel18)
                            .addComponent(txtPrecioVenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(cmdNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cmdAgregar1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdQuitar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSubtotalD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel15)
                            .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel16)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(cmdGuardar))))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(41, Short.MAX_VALUE)
                    .addComponent(lblSucursal)
                    .addContainerGap(562, Short.MAX_VALUE)))
        );

        setSize(new java.awt.Dimension(781, 666));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {

            CSelecciones.articulo = am.buscarPorCodigo(txtCodigo.getText(), configuraciones.getInstance().getSucursal());

            if (CSelecciones.articulo == null) {
                JOptionPane.showMessageDialog(rootPane, "No se encontro el artículo", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                CSelecciones.articulo.setSeries(sm.tieneSerie(CSelecciones.articulo));
                txtPrecio.setText(CSelecciones.articulo.getPunitario().toString());
                txtPrecioVenta.setText(CSelecciones.articulo.getPventa().toString());
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto3 = txtPrecio;
        CSelecciones.texto2 = txtPrecioVenta;
        new VSeleccionArticulo(true).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void txtPrecioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioKeyReleased
        // TODO add your handling code here:
        Validacion validar = new Validacion();
        validar.decimal(evt, txtPrecio);
    }//GEN-LAST:event_txtPrecioKeyReleased

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:

        if (CSelecciones.articulo != null) {
            double precio = 0;
            try {
                precio = Double.parseDouble(txtPrecio.getText()) / (1 + configuraciones.getInstance().getConfiguracion().getIva() / 100d);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Campo precio incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String serie = buscarSerie();
            if (serie == null) {
                limpiaTodo();
                return;
            }
            if (serie.equals("")) {
                agregarArticulo(precio, serie, Integer.parseInt(String.valueOf(txtCantidad.getValue())));
            } else {
                int cantidadAgregar = Integer.parseInt(String.valueOf(txtCantidad.getValue()));
                txtCantidad.setValue(1);
                for (int i = 0; i < cantidadAgregar - 1; i++) {
                    if (serie != null) {
                        agregarArticulo(precio, serie, 1);
                    }

                    serie = buscarSerie();
                }
                if (serie != null) {
                    agregarArticulo(precio, serie, 1);
                }
            }
            limpiaTodo();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un artículo", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void cmdNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNuevoActionPerformed
        // TODO add your handling code here:
        new VNuevoArticuloCompra(txtCodigo, txtPrecio, txtPrecioVenta).show();
    }//GEN-LAST:event_cmdNuevoActionPerformed

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:
        if (dtgFactura.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro", "Quitar Articulo", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int i = dtgFactura.getSelectedRow();
                modelo.removeRow(i);
                factura.getDetalleCompraList().remove(i);
                Calcular();
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un articulo", "Error", JOptionPane.ERROR_MESSAGE);
        }


    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void txtDescuentoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_txtDescuentoStateChanged
        // TODO add your handling code here:

    }//GEN-LAST:event_txtDescuentoStateChanged

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here:
        if (factura.getDetalleCompraList().size() > 0) {
            int numero = 0;
            try {
                numero = Integer.parseInt(txtNumFactura.getText());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Número de Factura incorrecto");
                return;
            }
            if (txtNumFactura.getText().length() == 0) {
                JOptionPane.showMessageDialog(rootPane, "Ingrese un número de factura");
                return;
            }
            if (fcm.buscarPorNumero(numero, listaProveedores.get(cboProveedor.getSelectedIndex())) != null) {
                JOptionPane.showMessageDialog(rootPane, "Ya existe una factura con este número");
                return;
            }
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro de guardar la factura?", "Guardar Factura", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                factura.setNumFactura(numero);
                factura.setIdProveedor(listaProveedores.get(cboProveedor.getSelectedIndex()));
                factura.setFechaEmision(dtFechaInicio.getDate());
                factura.setEstado(0);
                factura.setGuiaRemision(txtGuiaRemision.getText());
                factura.setIdSucursal(configuraciones.getInstance().getSucursal());
                fcm.guardarFactura(factura);
                VMantenimientoArticulos.getInstance().actualizaStocks();

                JOptionPane.showMessageDialog(rootPane, "Factura guardada correctamente", "Guardar Factura", JOptionPane.INFORMATION_MESSAGE);
                    //new CImprimir().imprimirFactura(factura);

                this.dispose();
            }
        }
    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void cmdAgregar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregar1ActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.articulo != null) {
            new VNuevoArticuloCompra(CSelecciones.articulo, txtCodigo, txtPrecio, txtPrecioVenta).show();
        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha seleccionado un artículo");
        }
    }//GEN-LAST:event_cmdAgregar1ActionPerformed

    private void txtPrecioVentaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioVentaKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPrecioVentaKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VFacturaCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VFacturaCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VFacturaCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VFacturaCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VFacturaCompra().setVisible(true);
            }
        });
    }

    private void limpiaTodo() {
        CSelecciones.articulo = null;
        txtCodigo.setText("");
        txtPrecio.setText("");
        txtPrecioVenta.setText("");
        txtCantidad.setValue(1);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboProveedor;
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdAgregar1;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdNuevo;
    private javax.swing.JButton cmdQuitar;
    private com.toedter.calendar.JDateChooser dtFechaInicio;
    private javax.swing.JTable dtgFactura;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblSucursal;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JSpinner txtDescuento;
    private javax.swing.JTextField txtGuiaRemision;
    private javax.swing.JTextField txtIVA;
    private javax.swing.JTextField txtNumFactura;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtPrecioVenta;
    private javax.swing.JTextField txtSubtotal;
    private javax.swing.JTextField txtSubtotalD;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
private String buscarSerie() {
        String serie = "";

        if (CSelecciones.articulo.getSeries()) {
            boolean serieValida = false;
            while (serie != null || !serieValida) {
                serieValida=true;
                serie = JOptionPane.showInputDialog("Ingrese un numero de serie");
                if (serie == null) {

                    return null;
                } else {
                    if (!sm.buscaSerie(CSelecciones.articulo, serie)) {
                        for (int i = 0; i < factura.getDetalleCompraList().size(); i++) {
                            if (factura.getDetalleCompraList().get(i).getSerie().equals(serie)) {
                                JOptionPane.showMessageDialog(rootPane, "Ya ha ingresado ese número de serie");
                                serieValida=false;
                            }
                        }

                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Ya existe ese número de serie");
                        serieValida=false;
                    }
                }
                if(serieValida)
                    return serie;
            }
        }
        return serie;
    }

    private void Calcular() {
        double subtotal = 0.0D;
        double iva = 0.0D;
        double desc = Double.parseDouble(String.valueOf(this.txtDescuento.getValue()));
        for (int i = 0; i < factura.getDetalleCompraList().size(); i++) {
            subtotal += factura.getDetalleCompraList().get(i).getCantidad() * factura.getDetalleCompraList().get(i).getPrecioCompra();

            double sd = factura.getDetalleCompraList().get(i).getCantidad() * factura.getDetalleCompraList().get(i).getPrecioCompra();
            sd = sd - sd * desc / 100.0D;
            iva += sd * configuraciones.getInstance().getConfiguracion().getIva() / 100.0D;
        }

        double subtd = subtotal - subtotal * desc / 100.0D;
        double total = subtd + iva;
        factura.setDescueto(desc);
        factura.setIva12(iva);
        factura.setSubtotal(subtotal);
        factura.setTotal(total);
        this.txtSubtotal.setText(CNumeros.Formato(subtotal));
        this.txtSubtotalD.setText(CNumeros.Formato(subtd));
        this.txtIVA.setText(CNumeros.Formato(iva));
        this.txtTotal.setText(CNumeros.Formato(total));
    }

    private void agregarArticulo(double precio, String serie, int cantidad) {
        boolean existe = false;
        if (serie.equals("")) {
            for (int i = 0; i < factura.getDetalleCompraList().size(); i++) {

                if (factura.getDetalleCompraList().get(i).getIdArticulo().getCodArticulo().equals(CSelecciones.articulo.getCodArticulo())) {
                    existe = true;
                    int nuevaCant = factura.getDetalleCompraList().get(i).getCantidad() + cantidad;
                    factura.getDetalleCompraList().get(i).setCantidad(nuevaCant);
                    dtgFactura.setValueAt(nuevaCant, i, 0);
                    dtgFactura.setValueAt(CNumeros.Formato(precio * nuevaCant), i, 3);
                    Calcular();

                    break;
                }
            }
        }
        if (!existe) {
            DetalleCompra detallefactura = new DetalleCompra();
            detallefactura.setCantidad(cantidad);
            detallefactura.setIdArticulo(CSelecciones.articulo);
            detallefactura.setIdFactura(factura);
            detallefactura.setIva(0d);
            detallefactura.setSerie(serie);
            detallefactura.setPrecioCompra(precio);
            factura.getDetalleCompraList().add(detallefactura);
            String desc = detallefactura.getIdArticulo().getDescripcion() + " " + detallefactura.getIdArticulo().getMarca() + " " + detallefactura.getIdArticulo().getModelo();
            if (!serie.equals("")) {
                desc = desc + "SN: " + serie;
            }
            String[] producto = {detallefactura.getCantidad().toString(), desc, CNumeros.Formato(precio), CNumeros.Formato(precio * cantidad)};
            modelo.addRow(producto);
            Calcular();

        }
    }

}
